package com.dzsw.utils;

import org.apache.commons.lang3.StringUtils;

import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BizUtil {

    /**
     * 生成注册短信验证码
     *
     * @return
     */
    public static String regVerifyCode() {
        String code = String.valueOf((int) (Math.random() * (9999 - 1000 + 1)) + 1000);
        return code;
    }

    /**
     * 获取Guid
     *
     * @return
     */
    public static String guid() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 引号转换
     *
     * @param str
     * @return
     */
    public static String quot2Sign(String str) {
        return str.replace("&quot;", "\"");
    }

    /**
     * 把字符串部分替换成指定char
     *
     * @param str      原字符串
     * @param lenFront 前面留几位 大于0有效
     * @param lenBack  后面留几位 大于0有效
     * @param chr      替换成的char
     * @return
     */
    public static String char2Star(String str, int lenFront, int lenBack, char chr) {
        if (StringUtils.isEmpty(str)) {
            return "";
        }
        int lenMiddle = str.length() - lenFront - lenBack;
        StringBuilder sb = new StringBuilder();
        if (lenFront > 0) {
            sb.append(str, 0, lenFront);
        }
        if (lenMiddle > 0) {
            sb.append(StringUtils.leftPad("", lenMiddle, chr));
        }
        if (lenBack > 0) {
            sb.append(str, str.length() - lenBack, str.length());
        }
        return sb.toString();
    }

    private static Pattern humpPattern = Pattern.compile("[A-Z]");

    /**
     * 驼峰转下划线
     *
     * @param str
     * @return
     */
    public static String humpToLine(String str) {
        Matcher matcher = humpPattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 计算处理次数
     *
     * @param total
     * @param numPerTimes
     * @return
     */
    public static int computeHandleTimes(int total, int numPerTimes) {
        if (total <= 0) {
            return 0;
        }
        if (total < numPerTimes) {
            return 1;
        }
        int times = total / numPerTimes;
        if (total % numPerTimes > 0) {
            return times + 1;
        } else {
            return times;
        }
    }

    public static void main(String[] args) {
        String str = "humpPattern";
        System.out.println(humpToLine(str));
        System.out.println(humpToLine("Str".toLowerCase()));

//        String phone = "18623456789";
//        String idCardNum = "211224199008080036";
//        String bankCardNum = "211224199008080036";
//        System.out.println(char2Star(phone, 3, 4, '*'));
//        System.out.println(char2Star(idCardNum, 3, 4, '*'));
//        System.out.println(char2Star(bankCardNum, 0, 4, '*'));
    }
}
